package com.yuntu.util;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author Dandan
 */
public final class ClazzConverter {
    private ClazzConverter() {
    }


    /**
     * 1.两个实体类互转
     * po转DTO
     * UserDTO userDTO = ClazzConverter.converterClass(userPO,UserDTO.class);
     *
     * 2.List<UserPO>转为List<UserDTO>
     * List<UserDTO> userDTOList = (List<UserDTO>)ClazzConverter.converterClass(userPOList,UserDTO.class);
     */

    //两个实体类互转
    public static <T1, T2> T1 converterClass(final T2 srcClazz, Class<T1> dstClazz) {
        String str = JSON.toJSONString(srcClazz);
        return str != null && !str.trim().equals("") ? JSON.parseObject(str.trim(), dstClazz) : null;
    }

    //转List
    public static <T1, T2> List<T1> converterClass(final List<T2> srcList, Class<T1> dstClazz) {
        List<T1> list = new ArrayList();
        if (srcList != null && !srcList.isEmpty()) {
            String str = JSON.toJSONString(srcList);
            if (str != null && !str.trim().equals("")) {
                list = JSON.parseArray(str.trim(), dstClazz);
                return (List)(list == null ? new ArrayList() : list);
            } else {
                return list;
            }
        } else {
            return list;
        }
    }

    public static <T1, T2> Collection<T1> converterClass(final Collection<T2> srcList, Class<T1> dstClazz) {
        List<T1> list = new ArrayList();
        if (srcList != null && !srcList.isEmpty()) {
            String str = JSON.toJSONString(srcList);
            if (str != null && !str.trim().equals("")) {
                Collection<T1> c = JSON.parseArray(str.trim(), dstClazz);
                return (Collection)(c == null ? list : c);
            } else {
                return list;
            }
        } else {
            return list;
        }
    }

}